import os
import uuid
from fastapi import UploadFile
from datetime import datetime

UPLOAD_DIR = "static/uploads"
ALLOWED_IMAGE_TYPES = {
    "image/jpeg",
    "image/png",
    "image/gif",
    "image/webp"
}

def get_file_extension(filename: str) -> str:
    """获取文件扩展名（包含点符号）"""
    return os.path.splitext(filename)[1].lower()

def generate_uuid_filename(original_filename: str) -> str:
    """生成UUID文件名"""
    ext = get_file_extension(original_filename)
    return f"{uuid.uuid4().hex}{ext}"

def create_date_dir(base_dir: str) -> str:
    """创建日期格式的目录并返回路径"""
    now = datetime.now()
    date_path = now.strftime("%Y/%m/%d")  # 格式：2025/05/12
    full_path = os.path.join(base_dir, date_path)
    
    # 自动递归创建目录
    os.makedirs(full_path, exist_ok=True)
    return full_path

async def save_upload_file(upload_file: UploadFile) -> str:
    """保存上传的文件（改进版）"""
    # 1. 验证文件类型
    if upload_file.content_type not in ALLOWED_IMAGE_TYPES:
        raise ValueError("不支持的文件类型")

    # 2. 创建日期目录
    date_dir = create_date_dir(UPLOAD_DIR)
    
    # 3. 生成唯一文件名
    filename = generate_uuid_filename(upload_file.filename)
    
    # 4. 保存文件
    file_path = os.path.join(date_dir, filename)
    content = await upload_file.read()
    with open(file_path, "wb") as f:
        f.write(content)

    # 5. 返回相对URL路径
    year, month, day = datetime.now().strftime("%Y/%m/%d").split("/")
    return f"/{UPLOAD_DIR}/{year}/{month}/{day}/{filename}"